package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service

public class ReportServiceimpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放葱begin开始的每天日期
        List<LocalDate> dateList=new ArrayList<>();
        List<Double> trunoverList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.isEqual(end))
        {begin=begin.plusDays(1);
        dateList.add(begin);
        }
        for (LocalDate date:dateList)
        {   //查询当天已完成的订单
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map=new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",5);
            Double turnover=orderMapper.sumByMap(map);
            turnover=turnover==null?0.0:turnover;
            trunoverList.add(turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(trunoverList,","))
            .build();
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        List<Long> newUserList=new ArrayList<>();
        List<Long> totalUserList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.isEqual(end))
        {   begin=begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate date:dateList)
        {   LocalDateTime beginTime=LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date,LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("end",endTime);
            Long totalUser=userMapper.countByMap(map);
            map.put("begin",beginTime);
            Long newUser=userMapper.countByMap(map);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList))
                .newUserList(StringUtils.join(newUserList))
                .totalUserList(StringUtils.join(totalUserList))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        List<Integer> orderCountList=new ArrayList<>();
        List<Integer> validOrderCountList=new ArrayList<>();
        Integer totalOrderCount=0;
        Integer validOrderCount=0;
        dateList.add(begin);
        while (!begin.isEqual(end))
        {   begin=begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate date:dateList)
        {
            LocalDateTime beginTime=LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date,LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("end",endTime);
            map.put("begin",beginTime);
            Integer orderCount=orderMapper.countByMap(map);
            map.put("status",5);
            Integer validOrder=orderMapper.countByMap(map);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrder);
            totalOrderCount+=orderCount;
            validOrderCount+=validOrder;
        }
        Double orderCompletionRate= totalOrderCount==0?0.0:Double.valueOf(validOrderCount)/totalOrderCount;
        return OrderReportVO.builder()
                .dateList(StringUtils.join(orderCountList))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList))
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime=LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end,LocalTime.MAX);
       List<GoodsSalesDTO> goodsSalesDTOList=orderMapper.getSaletTop(beginTime,endTime);
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出excel报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //查询数据，获得营业数据
        LocalDate dateBegin=LocalDate.now().minusDays(30);
        LocalDate dateend=LocalDate.now().minusDays(1);
        LocalDateTime begin=LocalDateTime.of(dateBegin,LocalTime.MIN);
        LocalDateTime end=LocalDateTime.of(dateend,LocalTime.MAX);
        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);
        //通过POI写入
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //填充数据--时间
            XSSFSheet sheet = excel.getSheet("sheet1");
            XSSFRow row = sheet.getRow(1);
            row.getCell(1).setCellValue("时间:"+dateBegin+"至"+dateend);
            //获得第四行
            row=sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //第五行
            row= sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());


            LocalDate date=dateBegin.minusDays(1);
            //订单明细
            for (int i=0;i<30;i++) {
                date=date.plusDays(1);
            //查询某一天的营业数据
            workspaceService.getBusinessData(LocalDateTime.of(dateBegin,LocalTime.MIN),LocalDateTime.of(dateBegin,LocalTime.MAX));
            row= sheet.getRow(7+i);
            row.getCell(1).setCellValue(String.valueOf(date));
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }
            //通过输出流下载
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
